# coding=utf-8
# 全世界最帅的帅哥
from io import BytesIO

from flask import request
from flask_restful import Resource

from ysgg1_club_oss.service.file_service import FileService


class OssResource(Resource):

    def get(self, action=None):
        pass

    def post(self, action=None):
        if action == "create_bucket":
            storage_service = FileService().storage_service()
            data = request.get_json()
            bucket_name = data.get("bucket_name")
            if not bucket_name:
                return {"message": "bucket_name is required"}, 400
            return storage_service.create_bucket(bucket_name)

        elif action == "upload_file":
            storage_service = FileService().storage_service()
            data = request.form
            bucket_name = data.get("bucket_name")
            file = request.files.get("file")

            # 创建一个内存中的文件对象来存储文件内容
            file_content = file.read()
            data_stream = BytesIO(file_content)
            length = len(file_content)

            file_name = file.filename
            if not bucket_name:
                return {"message": "bucket_name is required"}, 400
            return storage_service.upload_file(bucket_name, file_name, data_stream, length, file.content_type)

        elif action == "get_all_bucket":
            storage_service = FileService().storage_service()
            return storage_service.get_all_bucket()

        elif action == "get_all_file":
            storage_service = FileService().storage_service()
            return storage_service.get_all_bucket()

        elif action == "download_file":
            storage_service = FileService().storage_service()
            data = request.get_json()
            bucket_name = data.get("bucket_name")
            object_name = data.get("object_name")

            return storage_service.download_file(bucket_name, object_name)

        elif action == "remove_bucket":
            storage_service = FileService().storage_service()
            return storage_service.remove_bucket()

        elif action == "delete_object":
            storage_service = FileService().storage_service()
            return storage_service.remove_bucket()

        else:
            return {"code": 500, "message": "Wrong action"}
